﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public enum UIEffectMode
{
    Fade,
    Scale,
    Blink,
}

[RequireComponent(typeof(CanvasGroup))]
public class UIEffect : MonoBehaviour
{
    public GameObject Target;
    public UIEffectMode EffectMode;
    public Ease EaseMode = Ease.Unset;
    public bool AutoPlay = false;
    public float Duration = 0.1f;
    public float Delay = 0;

    [Tooltip("-1 for INFINITE")]
    public int Loop = 1;
    public LoopType LoopType = LoopType.Restart;

    public bool PingPong = false;

    public bool FromOffset = false;
    public Vector3 From;
    public Vector3 To;

    public bool PlayOnEnable = true;
    public bool PlayOnDisable = false;

    private Tweener m_Tweener;

    private void Awake()
    {
        if (Target == null)
        {
            Target = gameObject;
        }
    }

    private void OnEnable()
    {
        if (PlayOnEnable)
        {
            Play();
        }
    }

    private void OnDisable()
    {
        if (PlayOnDisable)
        {
            gameObject.SetActive(true);
        }
    }

    public void Show()
    {
        Target.SetActive(true);
        Play();
    }

    public void Hide()
    {
        Sequence seq = Play();
        seq.AppendCallback(() => Target.SetActive(false));
    }

    public Sequence Play()
    {
        Sequence seq = null;
        if (EffectMode == UIEffectMode.Fade)
        {
            seq = Fade();
        }
        // TODO...

        seq.SetEase(EaseMode);
        seq.SetDelay(Delay);

        return seq;
    }

    Sequence Fade()
    {
        CanvasGroup canvasGroup = null;
        if (!Target.TryGetComponent<CanvasGroup>(out canvasGroup))
        {
            canvasGroup = Target.AddComponent<CanvasGroup>();
        }

        if (FromOffset)
        {
            canvasGroup.alpha = From.x;
        }

        Sequence seq = DOTween.Sequence();
        seq.Append(canvasGroup.DOFade(To.x, Duration));
        return seq;
    }

    Sequence Scale()
    {
        if (FromOffset)
        {
            Target.transform.localScale = From;
        }

        Sequence seq = DOTween.Sequence();
        seq.Append(Target.transform.DOScale(To, Duration));
        // seq.SetLoops(Loop, LoopType);

        return seq;
    }

}
